package com.konsung.provide;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.text.TextUtils;
import com.konsung.bean.MeasureDataBean;
import com.konsung.bean.PatientBean;
import com.konsung.bean.PatientList;
import com.konsung.greendaoUtil.DBUtitl;
import com.konsung.greendaoUtil.GreenDaoManager;
import com.konsung.greendaoUtil.MeasureDataBeanDao;
import com.konsung.greendaoUtil.PatientBeanDao;
import com.konsung.util.DBDataUtil;
import com.konsung.util.DateUtil;
import com.konsung.util.IdCardUtil;
import com.konsung.util.JsonUtil;
import com.konsung.util.SpUtils;
import com.konsung.util.UiUtils;
import com.konsung.util.constant.GlobalConstant;

import org.greenrobot.greendao.query.LazyList;
import org.greenrobot.greendao.query.WhereCondition;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 内容提供 查询: app更新地址, 系统更新地址, 云平台地址, 设备号, 尿常规测量项配置, 设备配置参数,
 * 测量项配置参数, 快速检测配置参数
 */
public class ServiceProvider extends ContentProvider {

    //创建两个常量来区分不同的URI请求
    private static final int CURRENT_PATIENT = 1; //当前居民身份证
    private static final int UPDATE_MEASURE = 2; //更新测量数据
    private static final int UPDATE_MEASURE_ID = 3; //更新测量数据
    private static final int ADD_MEASURE = 4; //新增测量数据
    private static final int DELETE_MEASURE = 5; //删除测量数据
    private static final int QUERY_MEASURE_DATA = 6; //查询测量数据
    private static final int QUERY_MEASURE_DATA_NO = 13; //查询测量数据不排除已上传的
    private static final int QUERY_MEASURE_DATA_TEN = 7; //查询测量数据
    private static final int QUERY_MEASURE_PEOPLE_REPORT = 8; //查询测量记录人数
    private static final int QUERY_IDCARD_BEING = 9; //查询身份证号码是否已经存在
    private static final int QUERY_NEW_MEASURE = 10; //查询最新的测量记录
    private static final int ADD_ALL_MEASURE = 11; //批量添加测量数据
    private static final int ADD_ALL_PATIENT = 12; //批量添加居民档案
    private static final int QUERY_CURRENT_FIRST_MEASURE = 14; //查询测量数据
    private static final int INSERT_CITIZEN = 13; // 插入居民信息

    private static final String MEASUREDATABEAN = "MeasureDataBean"; //类名
    //构建key值数组
    private String[] keyArr = new String[]{GlobalConstant.CONFIG};

    private static UriMatcher uriMatcher; //填充匹配URI的容器

    //填充UriMatcher对象，其中以第二个参数区分数据类型
    static {
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        uriMatcher.addURI(GlobalConstant.AUTHORITY, GlobalConstant.CURRENT_PATIENT,
                CURRENT_PATIENT);
        uriMatcher.addURI(GlobalConstant.AUTHORITY, GlobalConstant.UPDATE_MEASURE,
                UPDATE_MEASURE);
        uriMatcher.addURI(GlobalConstant.AUTHORITY, GlobalConstant.UPDATE_MEASURE_ID,
                UPDATE_MEASURE_ID);
        uriMatcher.addURI(GlobalConstant.AUTHORITY, GlobalConstant.ADD_MEASURE,
                ADD_MEASURE);
        uriMatcher.addURI(GlobalConstant.AUTHORITY, GlobalConstant.DELETE_MEASURE,
                DELETE_MEASURE);
        uriMatcher.addURI(GlobalConstant.AUTHORITY, GlobalConstant.QUERY_MEASURE_DATA,
                QUERY_MEASURE_DATA);
        uriMatcher.addURI(GlobalConstant.AUTHORITY, GlobalConstant.QUERY_MEASURE_DATA_TEN,
                QUERY_MEASURE_DATA_TEN);
        uriMatcher.addURI(GlobalConstant.AUTHORITY, GlobalConstant.QUERY_MEASURE_PEOPLE_REPORT,
                QUERY_MEASURE_PEOPLE_REPORT);
        uriMatcher.addURI(GlobalConstant.AUTHORITY, GlobalConstant.QUERY_IDCARD_BEING,
                QUERY_IDCARD_BEING);
        uriMatcher.addURI(GlobalConstant.AUTHORITY, GlobalConstant.QUERY_NEW_MEASURE,
                QUERY_NEW_MEASURE);
        uriMatcher.addURI(GlobalConstant.AUTHORITY, GlobalConstant.ADD_ALL_MEASURE,
                ADD_ALL_MEASURE);
        uriMatcher.addURI(GlobalConstant.AUTHORITY, GlobalConstant.ADD_ALL_PATIENT,
                ADD_ALL_PATIENT);
        uriMatcher.addURI(GlobalConstant.AUTHORITY, GlobalConstant.QUERY_MEASURE_DATA_NO,
                QUERY_MEASURE_DATA_NO);
        uriMatcher.addURI(GlobalConstant.AUTHORITY, GlobalConstant.QUERY_CURRENT_FIRST_MEASURE,
                QUERY_CURRENT_FIRST_MEASURE);
        uriMatcher.addURI(GlobalConstant.AUTHORITY, GlobalConstant.INSERT_CITIZEN,
                INSERT_CITIZEN);
    }

    @Override
    public boolean onCreate() {
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {

        MatrixCursor matrixCursor = new MatrixCursor(keyArr, 1);
        try {
            switch (uriMatcher.match(uri)) {
                case CURRENT_PATIENT: //当前居民
                    String currentPatient = "";
                    PatientBean patientBean = DBUtitl.getCurrentPatient(getContext());
                    if (patientBean != null) {
                        currentPatient = JsonUtil.toJson(patientBean);
                    }
                    matrixCursor.addRow(new Object[]{currentPatient});
                    break;
                case QUERY_MEASURE_DATA: //查询当前居民未上传的最新测量数据
                    //获取当天时间0点
                    Date stop = new Date();
                    SimpleDateFormat dateFormat = UiUtils.getDateFormat(UiUtils.DateState.SHORT);
                    String format = dateFormat.format(stop);
                    Date star = dateFormat.parse(format);
                    MeasureDataBeanDao measureDataDao = GreenDaoManager.getMeasureDao(getContext());
                    String idCard = SpUtils.getSp(getContext(), GlobalConstant.APP_CONFIG,
                            GlobalConstant.CURRENT_PATIENT, "");
                    MeasureDataBean measureDataBean = null;
                    if (!TextUtils.isEmpty(idCard)) {
                        //测量时间倒叙，身份证相同，未上传，当天0点之后，现在时间之前
                        List<MeasureDataBean> query = measureDataDao.queryBuilder()
                                .orderDesc(MeasureDataBeanDao.Properties.MeasureTime)
                                .where(MeasureDataBeanDao.Properties.Idcard.eq(idCard))
                                .where(MeasureDataBeanDao.Properties.UploadFlag.eq(false))
                                .where(MeasureDataBeanDao.Properties.MeasureTime.ge(star.getTime()))
                                .where(MeasureDataBeanDao.Properties.MeasureTime.le(stop.getTime()))
                                .build()
                                .forCurrentThread()
                                .listLazy();
                        if (query != null && query.size() > 0) {
                            measureDataBean = query.get(0);
                            ((LazyList<MeasureDataBean>) query).close();
                        }
                    }

                    String data;
                    if (measureDataBean == null) {
                        data = "";
                    } else {
                        data = JsonUtil.toJson(measureDataBean);
                    }
                    matrixCursor.addRow(new Object[]{data});
                    break;
                case QUERY_CURRENT_FIRST_MEASURE: //查询当前居民最新测量数据
                    Calendar cNo = Calendar.getInstance(); //得到当前日期和时间
                    cNo.set(Calendar.HOUR, 0); //把当前时间小时变成0
                    cNo.set(Calendar.MINUTE, 0); //把当前时间分钟变成0
                    cNo.set(Calendar.SECOND, 0); //把当前时间秒数变成0
                    cNo.set(Calendar.MILLISECOND, 0); //把当前时间毫秒变成0
                    Date start = cNo.getTime();
                    MeasureDataBeanDao measureDataDaocNo =
                            GreenDaoManager.getMeasureDao(getContext());
                    String idCardcNo = SpUtils.getSp(getContext(), GlobalConstant.APP_CONFIG,
                            GlobalConstant.CURRENT_PATIENT, "");
                    MeasureDataBean measureDataBeancNo = null;
                    if (!TextUtils.isEmpty(idCardcNo)) {
                        WhereCondition ge = MeasureDataBeanDao.Properties.MeasureTime.ge(start
                                .getTime());
                        List<MeasureDataBean> query = measureDataDaocNo.queryBuilder()
                                .orderDesc(MeasureDataBeanDao.Properties.MeasureTime)
                                .where(MeasureDataBeanDao.Properties.Idcard.eq(idCardcNo))
                                .where(ge)
                                .build()
                                .forCurrentThread()
                                .listLazy();
                        if (query != null && query.size() > 0) {
                            measureDataBeancNo = query.get(0);
                            ((LazyList<MeasureDataBean>) query).close();
                        }
                    }

                    String datacNo;
                    if (measureDataBeancNo == null) {
                        datacNo = "";
                    } else {
                        datacNo = JsonUtil.toJson(measureDataBeancNo);
                    }
                    matrixCursor.addRow(new Object[]{datacNo});
                    break;
                case QUERY_MEASURE_DATA_NO:
                    Calendar cNo2 = Calendar.getInstance(); //得到当前日期和时间
                    cNo2.set(Calendar.HOUR, 0); //把当前时间小时变成0
                    cNo2.set(Calendar.MINUTE, 0); //把当前时间分钟变成0
                    cNo2.set(Calendar.SECOND, 0); //把当前时间秒数变成0
                    cNo2.set(Calendar.MILLISECOND, 0); //把当前时间毫秒变成0
                    Date cNo2Time = cNo2.getTime();
                    MeasureDataBeanDao measureDataDaocNo2 =
                            GreenDaoManager.getMeasureDao(getContext());
                    String idCardcNo2 = SpUtils.getSp(getContext(), GlobalConstant.APP_CONFIG,
                            GlobalConstant.CURRENT_PATIENT, "");
                    MeasureDataBean measureDataBeancNo2 = null;
                    if (!TextUtils.isEmpty(idCardcNo2)) {
                        WhereCondition ge = MeasureDataBeanDao.Properties.MeasureTime.ge(cNo2Time
                                .getTime());
                        List<MeasureDataBean> query = measureDataDaocNo2.queryBuilder()
                                .orderDesc(MeasureDataBeanDao.Properties.MeasureTime)
                                .where(MeasureDataBeanDao.Properties.Idcard.eq(idCardcNo2))
                                .where(ge)
                                .build()
                                .forCurrentThread()
                                .listLazy();
                        if (query != null && query.size() > 0) {
                            measureDataBeancNo2 = query.get(0);
                            ((LazyList<MeasureDataBean>) query).close();
                        }
                    }

                    String datacNo2;
                    if (measureDataBeancNo2 == null) {
                        datacNo2 = "";
                    } else {
                        datacNo2 = JsonUtil.toJson(measureDataBeancNo2);
                    }
                    matrixCursor.addRow(new Object[]{datacNo2});
                    break;

                case QUERY_MEASURE_DATA_TEN: //查询最近的10条测量记录
                    //由于10条心电数据过大，采用分次加载。
                    Integer startIndex;
                    Integer length;
                    try {
                        startIndex = Integer.valueOf(projection[0]);
                        length = Integer.valueOf(projection[1]);
                    } catch (Exception e) {
                        startIndex = 0;
                        length = 5;
                    }

                    String json = "";
                    String sp = SpUtils.getSp(getContext(), GlobalConstant.APP_CONFIG,
                            GlobalConstant.CURRENT_PATIENT, "");
                    if (!TextUtils.isEmpty(sp)) {
                        List<MeasureDataBean> query = GreenDaoManager.getMeasureDao(getContext())
                                .queryBuilder()
                                .offset(startIndex)
                                .limit(length)
                                .orderDesc(MeasureDataBeanDao.Properties.MeasureTime)
                                .where(MeasureDataBeanDao.Properties.Idcard.eq(sp))
                                .build()
                                .forCurrentThread()
                                .listLazy();

                        if (query != null && query.size() > 0) {
                            json = JsonUtil.toJson(query);
                            ((LazyList<MeasureDataBean>) query).close();
                        }
                    }
                    matrixCursor.addRow(new Object[]{json});
                    break;
                case QUERY_MEASURE_PEOPLE_REPORT: // 查询每个月测量人数的总数
                    List<Date> dateList = DateUtil.getAllMonFirstDate();
                    int[] arrInt = new int[dateList.size()];
                    MeasureDataBeanDao measureDao = GreenDaoManager.getMeasureDao(getContext());

                    for (int i = 0; i < dateList.size(); i++) {
                        Date stop3;
                        if (i + 1 == dateList.size()) {
                            stop3 = new Date();
                        } else {
                            stop3 = dateList.get(i + 1);
                        }

                        WhereCondition between = MeasureDataBeanDao.Properties.MeasureTime
                                .between(dateList.get(i).getTime(), stop3.getTime());
                        WhereCondition.StringCondition stringCondition = new WhereCondition
                                .StringCondition("IDCARD IS NOT NULL GROUP " +
                                "BY IDCARD HAVING COUNT(IDCARD) > 0");
                        LazyList<MeasureDataBean> measureDataBeen = measureDao.queryBuilder()
                                .where(between)
                                .where(stringCondition)
                                .build()
                                .forCurrentThread()
                                .listLazy();
                        arrInt[i] = measureDataBeen.size();
                        measureDataBeen.close();
                    }
                    matrixCursor.addRow(new Object[]{JsonUtil.toJson(arrInt)});
                    break;
                case QUERY_IDCARD_BEING: //查询身份证号码是否已存在
                    int size = 0;
                    if (projection != null && projection.length > 0) {
                        String idcard = projection[0];
                        PatientBeanDao patientDao = GreenDaoManager.getPatientDao(getContext());
                        List<PatientBean> patientBeen = patientDao.queryBuilder()
                                .where(PatientBeanDao.Properties.Idcard.eq(idcard))
                                .build()
                                .forCurrentThread()
                                .listLazy();
                        size = patientBeen.size();
                        ((LazyList<PatientBean>) patientBeen).close();
                    }
                    matrixCursor.addRow(new Object[]{size});
                    break;
                case QUERY_NEW_MEASURE: //查询最新的测量记录
                    MeasureDataBean newestMeasureData = DBUtitl.getNewestMeasure(getContext());
                    matrixCursor.addRow(new Object[]{JsonUtil.toJson(newestMeasureData)});
                    break;
                default:
                    return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //返回结果Cursor
        return matrixCursor;
    }

    @Override
    public String getType(Uri uri) {
        return null;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {

        int count = 0;

        switch (uriMatcher.match(uri)) {
            case DELETE_MEASURE:
                break;
            default:
                throw new IllegalArgumentException("Unkonw Uri:" + uri);
        }

        return count;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        long id = 0;
        try {
            switch (uriMatcher.match(uri)) {
                case ADD_MEASURE:
                    String str = values.getAsString(MEASUREDATABEAN);
                    MeasureDataBean sendMeasureBean = JsonUtil.toObject(str, MeasureDataBean.class);
                    String idcard = sendMeasureBean.getIdcard();
                    String uuid = sendMeasureBean.getUuid();

                    MeasureDataBeanDao measureDataDao = GreenDaoManager.getMeasureDao(getContext());
                    List<MeasureDataBean> list = measureDataDao.queryBuilder()
                            .where(MeasureDataBeanDao.Properties.Uuid.eq(uuid))
                            .list();

                    PatientBeanDao patientDao = GreenDaoManager.getPatientDao(getContext());
                    List<PatientBean> patientBeen = patientDao.queryBuilder()
                            .where(PatientBeanDao.Properties.Idcard.eq(idcard))
                            .list();

                    if (list != null && list.size() > 0) { //发送过来的数据本地已存在
                        MeasureDataBean measureDataBean = list.get(0);
                        sendMeasureBean.setId(measureDataBean.getId());
                        sendMeasureBean.setUploadFlag(false);
                        if (patientBeen != null && patientBeen.size() > 0) {
                            sendMeasureBean.setPatientId(patientBeen.get(0).getId());
                        }
                        measureDataDao.update(sendMeasureBean);
                        return ContentUris.withAppendedId(uri, 1);
                    } else {
                        // 更新居民对应的最新测量时间。
                        if (patientBeen != null && patientBeen.size() > 0) {
                            PatientBean patientBean = patientBeen.get(0);
                            patientBean.setCrimeMeasureDate(sendMeasureBean.getMeasureTime());
                            patientDao.update(patientBean);
                        }

                        //本地没有当前居民当天未上传的测量数据
                        Long id1 = new MeasureDataBean().getId();
                        sendMeasureBean.setId(id1);
                        sendMeasureBean.setPatientId(patientBeen.get(0).getId());
                        id = measureDataDao.insert(sendMeasureBean);
                        DBDataUtil.updatePatientUploadState(getContext(), idcard);
                    }


                    break;
                case ADD_ALL_MEASURE: //批量添加测量数据
                    String measureJson = values.getAsString(GlobalConstant.CONFIG);
                    MeasureDataBean measure = JsonUtil.toObject(measureJson, MeasureDataBean.class);
                    MeasureDataBeanDao measureDao = GreenDaoManager.getMeasureDao(getContext());
                    id = measureDao.insert(measure);
                    break;
                case ADD_ALL_PATIENT: // 批量添加居民档案
                    String patientJson = values.getAsString(GlobalConstant.CONFIG);
                    PatientBeanDao patientDao1 = GreenDaoManager.getPatientDao(getContext());
                    PatientList patientList = JsonUtil.toObject(patientJson, PatientList.class);
                    List<PatientBean> list1 = patientList.getList();
                    patientDao1.insertInTx(list1);
                    id = list1.size();
                    break;
                case INSERT_CITIZEN: // 插入居民信息
                    return insertCitizen(uri, values);
                default:
                    return Uri.EMPTY;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ContentUris.withAppendedId(uri, id);
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
            String[] selectionArgs) {
        int count = 0;

        switch (uriMatcher.match(uri)) {
            case UPDATE_MEASURE:
                String str = values.getAsString(MEASUREDATABEAN);
                MeasureDataBean measureDataBean = null;
                try {
                    measureDataBean = JsonUtil.toObject(str, MeasureDataBean.class);
                    GreenDaoManager.getMeasureDao(getContext()).update(measureDataBean);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            default:
                return -1;
        }

        return count;
    }

    /**
     * TODO 该TODO用于备忘，该uri用于处理公卫下载健康档案逻辑。当公卫下载健康档案时，
     * TODO 向健康档案app插入居民信息
     * 插入居民,基于GreenDao
     * @param uri Uri
     * @param values 传递过来的信息
     * @return 处理结果，返回uri。id= -1 属于已存在
     */
    private Uri insertCitizen(Uri uri, ContentValues values) {
        // 姓名
        String name = values.containsKey("name") ? values.getAsString("name") : "";
        // 身份证,为了查询方便，如果没有身份证，公卫会传-1过来
        String idcard = values.containsKey("idcard") ? values.getAsString("idcard") : "-1";
        // 年龄，如果没有设置年龄，公卫会传-1过来
        String age = values.containsKey("age") ? values.getAsString("age") : "-1";
        // 性别
        String gender = values.containsKey("gender") ? values.getAsString("gender") : "0";
        // 体重
        String weight = values.containsKey("weight") ? values.getAsString("weight") : "0";
        // 身高
        String height = values.containsKey("height") ? values.getAsString("height") : "0";
        // 血型
        String blood = values.containsKey("blood") ? values.getAsString("blood") : "4";
        String phone = values.containsKey("phone") ? values.getAsString("phone") : "";
        String address = values.containsKey("address") ? values.getAsString("address") : "";
        // 多应用的身份证字段是card, idcard是uuid
        WhereCondition idCardCondition = PatientBeanDao.Properties.Idcard.eq(idcard);
        List<PatientBean> list = GreenDaoManager.getInstance(getContext()).getSession()
                .getPatientBeanDao().queryBuilder()
                .where(idCardCondition).list();
        Uri result;
        if (list.size() > 0) {
            // 已经存在
            result = ContentUris.withAppendedId(uri, -1);
        } else {
            PatientBean bean = new PatientBean();
            bean.setName(name);
            if (!idcard.equals("-1")) {
                bean.setIdcard(idcard);
            }

            Date date = IdCardUtil.getAgeForIdCard(idcard);
            bean.setBirthday(date.getTime());
            if ("-1".equals(age)) {
                bean.setAge(IdCardUtil.getAge(date));
            } else {
                try {
                    bean.setAge(Integer.valueOf(age));
                } catch (Exception e) {
                    e.printStackTrace();
                    bean.setAge(0);
                }
            }
            bean.setWeight(Float.valueOf(weight));
            bean.setHeight(Float.valueOf(height));
            bean.setBlood(convertBlood(blood));
            bean.setContact(phone);
            bean.setAddress(address);
            try {
                bean.setSex(convertGender(Integer.valueOf(gender)));
            } catch (Exception e) {
                e.printStackTrace();
                bean.setSex(0);
            }
            PatientBeanDao patientDao = GreenDaoManager.getPatientDao(getContext());
            long id = patientDao.insertOrReplace(bean);
            result = ContentUris.withAppendedId(uri, id);
        }
        return result;
    }

    /**
     * TODO 备忘，用于处理从公卫获取的服务器返回的性别
     * 转换性别，服务器 0未知，1男，2女，9未说明的性别
     * @param serviceGender 服务器返回的性别
     * @return 本地保存的性别 0 - 女 | 1 - 男 ,其它默认女
     */
    private int convertGender(int serviceGender) {
//        switch (serviceGender) {
//            case 2:
//                return 0;
//            case 1:
//                return 1;
//            default:
//                return 0;
//        }
        return serviceGender;
    }

    /**
     * 8500血型转换,
     * @param blood 血型 0-A,1-B,2-O,3-AB,4-不详
     * @return 健康档案血型
     */
    public static int convertBlood(String blood) {
        // 无字典
        switch (blood) {
            case "0": // A
                return 1;
            case "1": // B
                return 2;
            case "2": // 0
                return 4;
            case "3": // AB
                return 3;
            case "4": // 不详
                return 0;
            default:
                return 0;
        }
    }

    /**
     * 查询居民当天未上传的测量数据
     * @param uuid 居民uuid
     * @return MeasureDataBean
     */
    private MeasureDataBean queryMeasureDataBean(String uuid) {
        try { //获取当天时间0点
            Date stop = new Date();
            SimpleDateFormat dateFormat = UiUtils.getDateFormat(UiUtils.DateState
                    .SHORT);
            String format = dateFormat.format(stop);
            Date star = null;
            star = dateFormat.parse(format);

            MeasureDataBeanDao measureDataDao = GreenDaoManager
                    .getMeasureDao(getContext());
            MeasureDataBean measureDataBean = null;
            if (!TextUtils.isEmpty(uuid)) {
                //测量时间倒叙，身份证相同，未上传，当天0点之后，现在时间之前
                WhereCondition startTime = MeasureDataBeanDao.Properties.MeasureTime
                        .ge(star.getTime());
                WhereCondition stopTime = MeasureDataBeanDao.Properties.MeasureTime
                        .le(stop.getTime());
                List<MeasureDataBean> query = measureDataDao.queryBuilder()
                        .where(MeasureDataBeanDao.Properties.Idcard.eq(uuid))
                        .where(MeasureDataBeanDao.Properties.UploadFlag.eq(false))
                        .where(startTime)
                        .where(stopTime)
                        .build()
                        .list();
                if (query != null && query.size() > 0) {
                    return query.get(0);
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }

}